package fts.ftsdata.services.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import fts.ftsdata.domain.ITag;
import fts.ftsdata.domain.ITaggedFile;
import fts.ftsdata.domain.impl.Tag;
import fts.ftsdata.domain.impl.TaggedFile;
import fts.ftsdata.services.ITaggingService;


public class TaggingService implements ITaggingService
{
	
	SessionFactory factory;
	LookupService lookupService;
	
	public TaggingService(SessionFactory fact, LookupService lookupService)
	{
		factory = fact;
		this.lookupService = lookupService;
	}

	public ITag createTag(String tag) throws Exception
	{
		System.out.println(Thread.currentThread().getStackTrace()[1]);

		Tag tagObj = lookupService.findTag(tag);
		
		if(tagObj == null)
		{
			tagObj =  new Tag(tag);
		}
		
		return tagObj;
	}

	public void saveTaggedFile(ITaggedFile file)
	{
		System.out.println(Thread.currentThread().getStackTrace()[1]);
		Session sess = getSession();
		try
		{
			sess.saveOrUpdate(file);
			sess.flush();
		}
		catch(Exception ex)
		{
			System.out.println(ex);
		}
		finally
		{
			sess.close();
		}
	}

	private Session getSession()
	{
		Session sess = factory.openSession();
		sess.enableFilter("autoTagFilter");
		sess.enableFilter("manualTagFilter");
		return sess;
	}

	public void deleteTaggedFile(ITaggedFile file)
	{
		System.out.println(Thread.currentThread().getStackTrace()[1]);
		Session sess = getSession();
		try
		{
			sess.delete(file);
			sess.flush();
		}
		catch(Exception ex)
		{
			System.out.println(ex);
		}
		finally
		{
			sess.close();
		}
	}

	public ITaggedFile createTaggedFile(String fileName) throws Exception
	{
		ITaggedFile file = lookupService.getFileByName(fileName);
		if(file == null)
		{
			file = new TaggedFile();
			file.setName(fileName);
			file.setIsAutoTagged(false);
		}
		return file;
	}

	
	public void deleteAutoTags()
	{
		Session sess = factory.openSession();
		try
		{
			sess.getNamedQuery("DeleteAutoTags").executeUpdate();
			sess.flush();
		}
		catch(Exception ex)
		{
			System.out.println(ex);
		}
		finally
		{
			sess.close();
		}
	}
}
